<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="rulePackageNo"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="'add'" :icon="CirclePlus" @click="addSLA">新增</el-button>
        <el-button type="primary" v-auth="'edit'" :icon="EditPen" @click="editSLA(scope.selectedList)">编辑</el-button>
        <el-button type="primary" plain @click="toDetail(scope.selectedList)">规则设置</el-button>
        <el-button
          type="danger"
          v-auth="'delete'"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedList)"
        >
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link v-auth="'edit'" :icon="EditPen" @click="editSLA([scope.row])">编辑</el-button>
        <el-button type="primary" link v-auth="'delete'" :icon="Delete" @click="batchDelete([scope.row])">删除</el-button>
      </template>
    </ProTable>
    <el-dialog title="新增/编辑" v-model="dialogTableVisible">
      <div :style="{ height: '500px' }">
        <el-tabs v-model="activeName" class="card" style="width: 100%; height: 500px">
          <el-tab-pane label="SLA明细" name="first">
            <el-form ref="ruleFormRef" :model="slaDtlFormData" style="width: 100%" label-width="120px">
              <el-form-item label="SLA名称 :" prop="contractName">
                <el-input v-model="slaDtlFormData.contractName" />
              </el-form-item>
              <el-form-item label="服务机构 :" prop="serviceOrgName">
                <el-tree-select
                  v-model="slaDtlFormData.serviceOrgName"
                  :data="treeFilterData"
                  check-strictly
                  :render-after-expand="false"
                  show-checkbox
                  check-on-click-node
                />
              </el-form-item>
              <el-form-item label="SLA版本 :" prop="versionNumber">
                <el-input v-model="slaDtlFormData.versionNumber" />
              </el-form-item>
              <el-form-item label="开始时间 :">
                <el-date-picker
                  v-model="slaDtlFormData.beginTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="结束时间 :">
                <el-date-picker
                  v-model="slaDtlFormData.endTime"
                  type="datetime"
                  placeholder="请选择结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="服务承诺 :" prop="agreement">
                <el-input v-model="slaDtlFormData.agreement" />
              </el-form-item>
              <el-form-item label="设置为默认sla :" prop="isDefault">
                <el-checkbox v-model="slaDtlFormData.isDefault" label="" size="large" />
                <!-- <el-input v-model="slaDtlFormData.isDefaultFlag" /> -->
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="被服务机构" name="second" style="width: 100%" label-width="120px">
            <el-tree-select
              style="width: 180px"
              v-model="ByServiceSelectValue"
              :data="ByServiceSelectList"
              multiple
              :render-after-expand="false"
              show-checkbox
              check-strictly
              check-on-click-node
            />
            <el-button type="primary" @click="addByService"> 添加 </el-button>

            <ProTable
              ref="byServiceProTable"
              row-key="id"
              :indent="20"
              :data="byServiceList"
              :columns="byServiceColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
              <!-- 表格操作 -->
              <template #operation="scope">
                <el-button type="primary" link @click="deletebyService(scope.$index)">删除</el-button>
              </template>
            </ProTable>
          </el-tab-pane>
          <el-tab-pane label="相关服务列表" name="three" style="width: 100%" label-width="120px">
            <el-tree-select
              style="width: 180px"
              v-model="ServiceListSelectValue"
              :data="ServiceListSelectList"
              multiple
              :render-after-expand="false"
              show-checkbox
              check-strictly
              check-on-click-node
            />
            <el-button type="primary" @click="addServiceList"> 添加 </el-button>

            <ProTable
              ref="ServiceProTable"
              row-key="id"
              :indent="20"
              :data="ServiceList"
              :columns="ServiceColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
              <!-- 表格操作 -->
              <template #operation="scope">
                <el-button type="primary" link @click="deleteService(scope.$index)">删除</el-button>
              </template>
            </ProTable>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-button type="primary" @click="onSubmit()"> 保存 </el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { User, RoleManager, OrgManager } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/accessControl/roleManagement/components/RoleDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import { getUserDepartment } from "@/api/modules/jggl";
import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import {
  FindSlaContractManagePage,
  getUserDepartmentList,
  editSlaContractManage,
  saveSlaContractManage,
  deleteSlaContractManage,
  findSlaById,
  findByServiceDir,
  findByOrgServices
} from "@/api/modules/slaProtocolManagement";
import { getCategoryTreeAllData } from "@/api/modules/dataDictionary";

const router = useRouter();

// const dialogTableVisible = ref(false);
// 跳转详情页
const toDetail = async (params: any[]) => {
  if (params.length == 1) {
    router.push(`/serviceLevel/SlaProtocolManagement/detail/${params[0].contractNo}?id=` + params[0].contractNo);
  } else {
    ElMessage.error("只能设置一条数据");
  }
};
const dialogTableVisible = ref(false);
// ProTable 实例
const proTable = ref<ProTableInstance>();

// ProTable 实例
const ServiceProTable = ref<ProTableInstance>();
const activeName = ref("first");
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const serviceInitParam = reactive({ type: 1 });
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const settingAuthRoleIds = ref("");
//子组件弹窗回调方法
const sendDataAddFrom = (data: any) => {
  setResourceByRoleIds(data + "-" + settingAuthRoleIds.value).then(res => {
    if (res.toString() == "true") {
      ElMessage.success("权限设置成功");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    } else {
      ElMessage.error("权限设置失败");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    }
  });
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "contractNo";
  newParams.sord = "desc";
  delete newParams.pageNum;
  delete newParams.pageSize;
  return FindSlaContractManagePage(newParams, "qdto", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};
export interface resList {
  agreement: string;
  beginTime: string;
  byServicesNos: [1, 2];
  string: string;
  companyNo: number;
  contractName: string;
  contractNo: number;
  dataFlag: number;
  dcode: number;
  dname: string;
  endTime: string;
  isDefault: boolean;
  lastUpdater: string;
  rulePackageNo: number;
  serviceDirNos: [];
  serviceOrgName: string;
  serviceOrgNo: number;
  versionNumber: string;
  orgNo: string;
  orgName: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "contractName", label: "名称", search: { el: "input" }, sortable: true },
  { prop: "serviceOrgName", label: "组织机构", sortable: true },
  { prop: "isDefault", label: "是否默认SLA", sortable: true, render: scope => <>{scope.row.isDefault === true ? "是" : "否"}</> },
  { prop: "versionNumber", label: "版本", sortable: true },
  { prop: "beginTime", label: "开始时间", sortable: true },
  { prop: "endTime", label: "结束时间", sortable: true },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  ElMessage.success("修改列表排序成功");
};

const slaDtlFormData = reactive({
  byServicesNosStr: "",
  servicesNosStr: "",
  contractNo: "",
  contractName: "",
  serviceOrgName: "",
  serviceOrgNo: "",
  isDefaultFlag: "false",
  isDefault: true,
  versionNumber: "",
  beginTime: "",
  endTime: "",
  agreement: "",
  dataFlag: 1
});
const SLAOption = ref("");
const onSubmit = async () => {
  if (slaDtlFormData.contractName == "") {
    ElMessage.error("请填写名称");
    activeName.value = "first";
    return;
  }
  if (slaDtlFormData.serviceOrgName == "") {
    ElMessage.error("请选择机构");
    activeName.value = "first";
    return;
  }
  if (slaDtlFormData.versionNumber == "") {
    activeName.value = "first";
    ElMessage.error("请填写版本");
    return;
  }
  if (slaDtlFormData.beginTime == "") {
    ElMessage.error("开始时间不能为空");
    activeName.value = "first";
    return;
  }
  if (slaDtlFormData.endTime == "") {
    ElMessage.error("结束时间不能为空");
    activeName.value = "first";
    return;
  }
  if (slaDtlFormData.beginTime > slaDtlFormData.endTime) {
    ElMessage.error("开始时间不能大于结束时间");
    activeName.value = "first";
    return;
  }
  if (slaDtlFormData.agreement == "") {
    ElMessage.error("服务承诺不能为空");
    activeName.value = "first";
    return;
  }
  if (byServiceList.value.length == 0) {
    ElMessage.error("请选择被服务机构");
    activeName.value = "second";
    return;
  }

  traverseTree(ByServiceSelectList.value[0], node => {
    if (node.value == slaDtlFormData.serviceOrgName) {
      slaDtlFormData.serviceOrgNo = node.attr.orgNo;
    }
  });

  // slaDtlFormData["isDefault"] = slaDtlFormData.isDefault == true ? true : false;

  let byServicesNosStr = "";
  for (let i = 0; i < byServiceList.value.length; i++) {
    if (byServicesNosStr == "") {
      byServicesNosStr = byServiceList.value[i].orgNo.toString();
    } else {
      byServicesNosStr += "," + byServiceList.value[i].orgNo.toString();
    }
  }
  slaDtlFormData.byServicesNosStr = byServicesNosStr;

  //相关服务
  let ServicesNosStr = "";
  for (let i = 0; i < ServiceList.value.length; i++) {
    if (ServicesNosStr == "") {
      ServicesNosStr = ServiceList.value[i].id.toString();
    } else {
      ServicesNosStr += "," + ServiceList.value[i].id.toString();
    }
  }
  slaDtlFormData.servicesNosStr = ServicesNosStr;
  if (SLAOption.value == "add") {
    slaDtlFormData.contractNo = "";
    saveSlaContractManage(slaDtlFormData, "slaContractDTO", ["byServicesNosStr", "servicesNosStr"]).then(res => {
      if (res == null) {
        ElMessage.success("保存成功");
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
        dialogTableVisible.value = false;
      } else {
        ElMessage.error("保存失败");
      }
    });
  } else {
    editSlaContractManage(slaDtlFormData, "slaContractDTO", ["byServicesNosStr", "servicesNosStr"]).then(res => {
      if (res == null) {
        ElMessage.success("编辑成功");
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
        dialogTableVisible.value = false;
      } else {
        ElMessage.error("编辑失败");
      }
    });
  }
};

// 批量删除
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?contractNos=" + id[i].contractNo;
    } else {
      idsStr = idsStr + "&contractNos=" + id[i].contractNo;
    }
    NameStr = NameStr + id[i].contractName + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      deleteSlaContractManage(idsStr).then(res => {
        if (res.toString() == "true") {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          proTable.value?.clearSelection();
          proTable.value?.getTableList();
        } else {
          ElMessage({
            type: "error",
            message: "存在关联数据无法删除，请检查"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const treeFilterData = ref<any>([]);
const ByServiceSelectValue = ref();
const ByServiceSelectList = ref<any>([]);
const ServiceListSelectValue = ref();
const ServiceListSelectList = ref<any>([]);
const addSLA = () => {
  slaDtlFormData.contractName = "";
  slaDtlFormData.serviceOrgName = "";
  slaDtlFormData.serviceOrgNo = "";
  slaDtlFormData.isDefaultFlag = "false";
  slaDtlFormData.isDefault = false;
  slaDtlFormData.versionNumber = "";
  slaDtlFormData.beginTime = "";
  slaDtlFormData.endTime = "";
  slaDtlFormData.agreement = "";
  slaDtlFormData.contractNo = "";
  SLAOption.value = "add";
  dialogTableVisible.value = true;
  getUserDepartment().then(res => {
    let newres = JSON.parse(JSON.stringify(res));
    traverseTree(newres[0], node => {
      node.lable = node.attr.orgNo;
      node.value = node.attr.orgName;
    });
    treeFilterData.value = newres;
    ByServiceSelectList.value = newres;
  });
  ByServiceSelectValue.value = null;
  byServiceList.value = [];
  getCategoryTreeAllData("Service").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    ServiceListSelectList.value = [res as any];
  });
  ServiceListSelectValue.value = null;
  ServiceList.value = [];
  return;
};
const editSLA = async (params: any[]) => {
  SLAOption.value == "edit";
  if (params.length == 1) {
    getUserDepartment().then(res => {
      let newres = JSON.parse(JSON.stringify(res));
      traverseTree(newres[0], node => {
        node.lable = node.attr.orgNo;
        node.value = node.attr.orgName;
      });
      treeFilterData.value = newres;
      ByServiceSelectList.value = newres;
    });
    slaDtlFormData.contractNo = params[0].contractNo;
    findSlaById(params[0].contractNo).then(res => {
      let newParams = JSON.parse(JSON.stringify(res));
      slaDtlFormData.contractName = newParams.contractName;
      slaDtlFormData.serviceOrgName = newParams.serviceOrgName;
      slaDtlFormData.serviceOrgNo = newParams.serviceOrgNo;
      slaDtlFormData.isDefaultFlag = newParams.isDefault == "false" ? "false" : "true";
      slaDtlFormData.isDefault = newParams.isDefault.toString() == "false" ? false : true;
      slaDtlFormData.versionNumber = newParams.versionNumber;
      slaDtlFormData.beginTime = newParams.beginTime;
      slaDtlFormData.endTime = newParams.endTime;
      slaDtlFormData.agreement = newParams.agreement;
      // slaDtlFormData.contractNo = newParams.contractNo;
      dialogTableVisible.value = true;
    });
    ByServiceSelectValue.value = null;
    byServiceList.value = [];
    findByOrgServices(params[0].contractNo).then(res => {
      let newParams = JSON.parse(JSON.stringify(res));
      (res.data as any).forEach(function (tmpselect) {
        let selectObj = {};
        selectObj["orgNo"] = tmpselect.orgNo;
        selectObj["orgName"] = tmpselect.orgName;
        byServiceList.value.push(selectObj);
      });
    });
    ServiceListSelectValue.value = null;
    ServiceList.value = [];
    getCategoryTreeAllData("Service").then(res => {
      // 使用traverseTree遍历树
      traverseTree(res as any, node => {
        node["lable"] = node.attr.cname;
        node["value"] = node.attr.cname;
      });
      ServiceListSelectList.value = [res as any];
    });
    findByServiceDir(params[0].contractNo).then(res => {
      let newParams = JSON.parse(JSON.stringify(res));
      (res.data as any).forEach(function (tmpselect) {
        let selectObj = {};
        selectObj["id"] = tmpselect.eventId;
        selectObj["cname"] = tmpselect.eventName;
        ServiceList.value.push(selectObj);
      });
    });
  } else {
    ElMessage.error("只能编辑一条数据");
  }
};
interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  lable: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}

const byServiceProTable = ref<ProTableInstance>();
const byServiceColumns = reactive<ColumnProps<resList>[]>([
  { prop: "orgNo", label: "id", sortable: true, width: 200 },
  { prop: "orgName", label: "名称", sortable: true },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);
const ServiceColumns = reactive<ColumnProps<resList>[]>([
  { prop: "id", label: "id", sortable: true, width: 200 },
  { prop: "cname", label: "服务名称", sortable: true },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);
const byServiceList = ref<any>([]);
const ServiceList = ref<any>([]);
const byService = reactive({
  orgName: "",
  orgNo: ""
});
const Service = reactive({
  cname: "",
  id: ""
});
// 删除
const deletebyService = async (index: any) => {
  byServiceList.value.splice(index, 1);
};
// 删除相关服务
const deleteService = async (index: any) => {
  ServiceList.value.splice(index, 1);
};

//添加相关服务列表
const addServiceList = async () => {
  let tmpselectList: any = [];
  ServiceListSelectValue.value.forEach(function (element2) {
    traverseTree(ServiceListSelectList.value[0], node => {
      if (node.data == element2.toString()) {
        let selectObj = {};
        selectObj["id"] = node.attr.id;
        selectObj["cname"] = node.attr.cname;
        tmpselectList.push(selectObj);
      }
    });
  });
  tmpselectList.forEach(function (tmpselect) {
    if (ServiceList.value.length == 0) {
      ServiceList.value.push(tmpselect);
    } else {
      let flag = "true";
      for (let i = 0; i < ServiceList.value.length; i++) {
        if (ServiceList.value[i].cname == tmpselect["cname"]) {
          flag = "false";
        }
      }
      if (flag == "true") {
        ServiceList.value.push(tmpselect);
      } else {
        ElMessage({
          type: "info",
          message: "存在相同服务 :   " + tmpselect["cname"] + "，  已自动过滤重复服务"
        });
      }
    }
  });
};
//添加被服务机构
const addByService = async () => {
  let tmpselectList: any = [];
  ByServiceSelectValue.value.forEach(function (element2) {
    traverseTree(ByServiceSelectList.value[0], node => {
      if (node.value == element2.toString()) {
        let selectObj = {};
        selectObj["orgNo"] = node.attr.orgNo;
        selectObj["orgName"] = node.attr.orgName;
        tmpselectList.push(selectObj);
      }
    });
  });
  tmpselectList.forEach(function (tmpselect) {
    if (byServiceList.value.length == 0) {
      byServiceList.value.push(tmpselect);
    } else {
      let flag = "true";
      for (let i = 0; i < byServiceList.value.length; i++) {
        if (byServiceList.value[i].orgName == tmpselect["orgName"]) {
          flag = "false";
        }
      }
      if (flag == "true") {
        byServiceList.value.push(tmpselect);
      } else {
        ElMessage({
          type: "info",
          message: "存在相同机构 :   " + tmpselect["orgName"] + "，  已自动过滤重复机构"
        });
      }
    }
  });
};
</script>
